package org.ihelpuoo.orm.handler.dom;

import java.lang.reflect.Field;

import javax.xml.xpath.XPathConstants;

import org.ihelpuoo.lang.StringUtils;
import org.ihelpuoo.orm.FieldRule;
import org.ihelpuoo.orm.IIIException;
import org.ihelpuoo.orm.ObjectRule;
import org.ihelpuoo.orm.handler.ObjectProcessor;
import org.ihelpuoo.orm.handler.ReadNormalFieldHandler;
import org.ihelpuoo.xml.XMLUtils;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

public class EleReadNormalFieldHandler extends ReadNormalFieldHandler
{

	public EleReadNormalFieldHandler(ObjectProcessor beanHandler)
	{
		super(beanHandler);
	}

	@Override
	protected Object evalObjectValue(ObjectRule r, Field f, Object src, String prefix) throws Exception
	{
		String v = null;
		String nn = null;
		int nodeType = r.getDomNodeType(f);
		switch (nodeType)
		{
		case FieldRule.ATTRIBUTE_NODE:
			nn = r.getDomNodeName(f);
			if (!((Element)src).hasAttribute(nn))
				return null;
			v = ((Element)src).getAttribute(nn);
			break;
		case FieldRule.ELEMENT_NODE:
			nn = r.getDomNodeName(f);
			Element child = (Element)this.processor.getManual().xpath().newXPath().evaluate(
					"./" + nn + "[1]",src,XPathConstants.NODE);
			if (null != child)
				v = child.getTextContent();
			break;
		case FieldRule.TEXT_NODE:
			v = ((Element)src).getTextContent();
			break;
		case FieldRule.COMMENT_NODE:
			Node prev = ((Node)src).getPreviousSibling();
			if (!XMLUtils.isComment(prev))
				if (XMLUtils.isText(prev) && StringUtils.isBlank(prev.getTextContent()))
					prev = prev.getPreviousSibling();
			if (XMLUtils.isComment(prev))
				v = prev.getTextContent();
			break;
		default:
			throw new IIIException("Unknow field type '" + nodeType + "' of field '" + f.getName()
					+ "' of class '" + r.getType().getName() + "'");
		}
		return v;
	}

}
